<template>
  <div class="app-container" style="overflow-x: hidden;">
    <br>
     <el-form :model="orderForm" ref="orderForm" label-width="80px" :rules="orderFormRules">
      <el-row :gutter=10>
        <h3>审批信息</h3>
        <el-col :span=8 >
          <el-form-item :label="(index+1)+'级审批'" v-for="(jobDuty, index) in this.auditPreset" :key="jobDuty.id" prop="auditPreset">
            <span>{{ jobDuty.name }}</span>
            <el-select v-model="jobDuty.auditUser" placeholder="请选择" style="width: 100%" :disabled="orderForm.status != 0">
              <el-option
                v-for="item in jobDuty.auditAvailableUserList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter=10>
        <h3>采集信息</h3>
        <el-col :span=6>
          <el-form-item label="供货商" prop="supplier" >
            <el-select style="width: 100%;" v-model="orderForm.supplier" placeholder="请选择" :disabled="orderForm.status != 0">
              <el-option
                v-for="item in suppliers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <br>
    <el-button type="primary" v-if="orderForm.status === 1" @click="add">添加商品</el-button>
    <br>
    <div style="display: flex;justify-content: left">
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="序号" min-width="40" >
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="编码" min-width="130" align="center" >
          <template slot-scope="scope">
            {{ scope.row.drugCode }}
          </template>
        </el-table-column>
        <el-table-column label="名称" min-width="150" align="center" >
          <template slot-scope="scope">
            {{ scope.row.drugName }}
          </template>
        </el-table-column>
        <el-table-column label="规格" min-width="130" align="center" >
          <template slot-scope="scope">
            {{ scope.row.drugSpecs }}
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="80" align="center" >
          <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusNameFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最低采购量" min-width="100" align="center" >
          <template slot-scope="scope">
            {{ scope.row.minPurchaseNum }}
          </template>
        </el-table-column>
        <el-table-column label="采购周期" min-width="80" align="center" >
          <template slot-scope="scope">
            {{ scope.row.buyCycle }}
          </template>
        </el-table-column>
        <el-table-column
          :label="header.label"
          v-for="(header, index) in tableFilter"
          :key="header.prop"
          align="center"
        >
          <el-table-column label="现库存" :prop="`drugDepositoryVoList.${index}.inventory`" width="120px" align="center" ></el-table-column>
          <el-table-column label="采购" :prop="`drugDepositoryVoList.${index}.purchaseNum`" width="120px" align="center" ></el-table-column>
          <!-- <el-table-column label="操作" :prop="`drugDepositoryVoList.${index}.operationList`" width="120px" align="center" v-for="operation in operationList[`${index}`]" :key="operation" >
            {{ operation }}
          </el-table-column> -->
          <el-table-column label="完成后库存" :prop="`drugDepositoryVoList.${index}.doneInventory`" width="120px" align="center" ></el-table-column>
        </el-table-column>
        <el-table-column class-name="status-col" label="操作" align="center" width="300" >
          <template slot-scope="scope">
            <el-button type="primary" v-if="orderForm.status === 0"  @click="operation(scope.row, scope.$index)" size="small">操作</el-button>
            <el-button type="primary" v-else  @click="operation(scope.row, scope.$index)" size="small">查看</el-button>
            <el-button type="success" v-if="orderForm.status === 1"  @click="updateOperation(scope.row, scope.$index)" size="small">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="footer">
      <el-button type="warning" v-if="orderForm.status === 0" :loading="commitBtnLoading" @click="confirm(0)">保存</el-button>
      <div style="width:200px;display: inline-block;"> </div>
      <el-button type="primary" v-if="orderForm.status === 0 || isReUpdate" :loading="commitBtnLoading" @click="confirm(1)">提交</el-button>
      <div style="width:100px;display: inline-block;"> </div>
      <el-button @click="cancel">取 消</el-button>
    </div>
  
    <el-dialog :title="dialogTitle" :visible.sync="formVisible" width="1200px" :close-on-click-modal="false" >
      <h2>基本信息</h2>
      <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
        <el-row :gutter="10">
          <el-col :span=8>
            <el-form-item label="药品编码" >
                <el-input v-model="form.drugCode" :disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span=8>
            <el-form-item label="药品名称" >
                <el-input v-model="form.drugName" :disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span=8>
            <el-form-item label="药品规格" >
                <el-input v-model="form.drugSpecs" :disabled="true" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <br>
        <br>
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for=" (operation, index) in form.operationList" :key="operation.id">
            <el-row :gutter="10" v-if="operation.operationType == 1" >
              <el-col :span=1>
                <el-button type="danger" icon="el-icon-delete" circle @click="form.operationList.splice(index, 1)" v-if="orderForm.status === 0"></el-button>
              </el-col>
              <el-col :span=5 >
                <el-form-item label="操作类型" prop="operationType">
                    <el-select style="width: 100%;" v-model="operation.operationType" placeholder="请选择" :disabled="orderForm.status === 1">
                      <el-option
                        v-for="item in operationTypeEnum"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        @click.native="clickOperationType(operation)"
                        >
                      </el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="来源库">
                  <el-select style="width: 100%;" v-model="operation.sourceDepositoryId" placeholder="请选择" :disabled="orderForm.status != 0">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="数量" >
                    <el-input type="Number" min=0 v-model="operation.num" :disabled="orderForm.status != 0"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="目标库">
                  <el-select style="width: 100%;" v-model="operation.targetDepositoryId" placeholder="请选择" :disabled="orderForm.status != 0">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-else>
              <el-col :span=1>
                <el-button type="danger" icon="el-icon-delete" circle @click="form.operationList.splice(index, 1)" v-if="orderForm.status === 0"></el-button>
              </el-col>
              <el-col :span=5 >
                <el-form-item label="操作类型" prop="operationType">
                    <el-select style="width: 100%;" v-model="operation.operationType" placeholder="请选择" :disabled="orderForm.status != 0">
                      <el-option
                        v-for="item in operationTypeEnum"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        @click.native="clickOperationType(operation)"
                        >
                      </el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="数量" >
                    <el-input type="Number" min=0 v-model="operation.num" :disabled="orderForm.status != 0">
                    </el-input>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="目标库">
                  <el-select style="width: 100%;" v-model="operation.targetDepositoryId" placeholder="请选择" :disabled="orderForm.status != 0">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="form.operationList.push({operationType: 1})" v-if="orderForm.status === 0">添加</el-button>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmOperation">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancelOperation">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="dialogTitle" :visible.sync="updateFormVisible" width="1200px" :close-on-click-modal="false" >
      <h2>基本信息</h2>
      <el-form ref="updateForm" :model="updateForm" label-width="80px" :rules="formRules">
        <el-row :gutter="10">
          <el-col :span=8>
            <el-form-item label="药品编码" >
                <el-input v-model="updateForm.drugCode" :disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span=8>
            <el-form-item label="药品名称" >
              <el-autocomplete
                value-key="pinyinCode"
                class="inline-input"
                v-model="searchValue"
                :fetch-suggestions="querySearch"
                placeholder="请输入 拼音简码"
                :trigger-on-focus="false"
                @select="handleSelect"
                style="width: 100%;"
              >
                <template slot-scope="{ item }">
                  <span >{{ item.name+'/' }}</span>
                  <span >{{ item.commonName+' ' }}</span>
                  <span >{{ item.form+' ' }}</span>
                  <span >{{ item.specs+' '  }}</span>
                  <span >{{ item.factory }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span=8>
            <el-form-item label="药品规格" >
                <el-input v-model="updateForm.drugSpecs" :disabled="true" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <br>
        <br>
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for=" (operation, index) in updateForm.operationList" :key="operation.id">
            <el-row :gutter="10" v-if="operation.operationType == 1" >
              <el-col :span=1>
                <el-button type="danger" icon="el-icon-delete" circle @click="updateForm.operationList.splice(index, 1)" v-if="orderForm.status === 1"></el-button>
              </el-col>
              <el-col :span=5 >
                <el-form-item label="操作类型" prop="operationType">
                    <el-select style="width: 100%;" v-model="operation.operationType" placeholder="请选择" :disabled="orderForm.status != 1">
                      <el-option
                        v-for="item in operationTypeEnum"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        @click.native="clickOperationType(operation)"
                        >
                      </el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="来源库">
                  <el-select style="width: 100%;" v-model="operation.sourceDepositoryId" placeholder="请选择" :disabled="orderForm.status != 1">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="数量" >
                    <el-input type="Number" min=0 v-model="operation.num" :disabled="orderForm.status != 1"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="目标库">
                  <el-select style="width: 100%;" v-model="operation.targetDepositoryId" placeholder="请选择" :disabled="orderForm.status != 1">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-else>
              <el-col :span=1>
                <el-button type="danger" icon="el-icon-delete" circle @click="updateForm.operationList.splice(index, 1)" v-if="orderForm.status == 1"></el-button>
              </el-col>
              <el-col :span=5 >
                <el-form-item label="操作类型" prop="operationType">
                    <el-select style="width: 100%;" v-model="operation.operationType" placeholder="请选择" :disabled="orderForm.status != 1">
                      <el-option
                        v-for="item in operationTypeEnum"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        @click.native="clickOperationType(operation)"
                        >
                      </el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="数量" >
                    <el-input type="Number" min=0 v-model="operation.num" :disabled="orderForm.status != 1">
                    </el-input>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="目标库">
                  <el-select style="width: 100%;" v-model="operation.targetDepositoryId" placeholder="请选择" :disabled="orderForm.status != 1">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="updateForm.operationList.push({operationType: 2})" v-if="orderForm.status == 1">添加</el-button>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmUpdateOperation">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancelOperation">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="dialogTitle" :visible.sync="addFormVisible" width="1200px" :close-on-click-modal="false" >
      <h2>基本信息</h2>
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="formRules">
        <el-row :gutter="10">
          <el-col :span=8>
            <el-form-item label="药品编码" >
                <el-input v-model="addForm.drugCode" :disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span=8>
            <el-form-item label="药品名称" >
              <el-autocomplete
                value-key="pinyinCode"
                class="inline-input"
                v-model="searchValue"
                :fetch-suggestions="querySearch"
                placeholder="请输入 拼音简码"
                :trigger-on-focus="false"
                @select="handleSelect"
                style="width: 100%;"
              >
                <template slot-scope="{ item }">
                  <span >{{ item.name+'/' }}</span>
                  <span >{{ item.commonName+' ' }}</span>
                  <span >{{ item.form+' ' }}</span>
                  <span >{{ item.specs+' '  }}</span>
                  <span >{{ item.factory }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span=8>
            <el-form-item label="药品规格" >
                <el-input v-model="addForm.drugSpecs" :disabled="true" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <br>
        <br>
        <div style="width:100%;border: 2px solid #E4E7ED;padding: 10px;">
          <div v-for=" (operation, index) in addForm.operationList" :key="operation.id">
            <el-row :gutter="10" v-if="operation.operationType == 1" >
              <el-col :span=1>
                <el-button type="danger" icon="el-icon-delete" circle @click="addForm.operationList.splice(index, 1)" v-if="orderForm.status === 1"></el-button>
              </el-col>
              <el-col :span=5 >
                <el-form-item label="操作类型" prop="operationType">
                    <el-select style="width: 100%;" v-model="operation.operationType" placeholder="请选择" :disabled="orderForm.status != 1">
                      <el-option
                        v-for="item in operationTypeEnum"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        @click.native="clickOperationType(operation)"
                        >
                      </el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="来源库">
                  <el-select style="width: 100%;" v-model="operation.sourceDepositoryId" placeholder="请选择" :disabled="orderForm.status != 1">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="数量" >
                    <el-input type="Number" min=0 v-model="operation.num" :disabled="orderForm.status != 1"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="目标库">
                  <el-select style="width: 100%;" v-model="operation.targetDepositoryId" placeholder="请选择" :disabled="orderForm.status != 1">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10" v-else>
              <el-col :span=1>
                <el-button type="danger" icon="el-icon-delete" circle @click="addForm.operationList.splice(index, 1)" v-if="orderForm.status == 1"></el-button>
              </el-col>
              <el-col :span=5 >
                <el-form-item label="操作类型" prop="operationType">
                    <el-select style="width: 100%;" v-model="operation.operationType" placeholder="请选择" :disabled="orderForm.status != 1">
                      <el-option
                        v-for="item in operationTypeEnum"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                        @click.native="clickOperationType(operation)"
                        >
                      </el-option>
                    </el-select>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="数量" >
                    <el-input type="Number" min=0 v-model="operation.num" :disabled="orderForm.status != 1">
                    </el-input>
                </el-form-item>
              </el-col>
              <el-col :span=6>
                <el-form-item label="目标库">
                  <el-select style="width: 100%;" v-model="operation.targetDepositoryId" placeholder="请选择" :disabled="orderForm.status != 1">
                    <el-option
                      v-for="item in depositoryEnum"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" @click="addForm.operationList.push({operationType: 2})" v-if="orderForm.status == 1">添加</el-button>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmAddOperation">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancelOperation">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { queryDepositoryNumList, queryDepositoryNumDetail, allDrugDepositoryNum, getListByPinyinCode, drugDepositoryNum } from '@/api/drug'
import { getInfo as getPurchaseOrderInfo, addorupdate } from '@/api/purchaseOrder'
import template from './../guidance/template.vue'
import { getList as getSupplierList } from '@/api/supplier'
import { getInfo as getAuditInfo } from '@/api/auditFlow'

export default {
  filters: {
    statusColorFilter(status) {
      const statusMap = ['danger', 'primary', 'warning']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['下架', '上架', '欲下架']
      return statusMap[status]
    }
  },
  data() {
    const validateOperationType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择操作类型')) 
      else callback()
    }
    const validateSupplier = (rule, value, callback) => {
      if (!value) callback(new Error('请选择供货商'))
      else callback()
    }
    const validateAuditPreset = (rule, value, callback) => {
      for (let index = 0; index < this.auditPreset.length; index++) {
        if(this.orderForm.status === 1 && !this.auditPreset[index].auditUser) callback(new Error('请选择审批人'))
      }
      callback()
    }
    return {
      list: [],
      listLoading: true,
      toUpdateBtnLoading: false,
      toInfoBtnLoading: false,
      commitBtnLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      updateFormVisible: false,
      addFormVisible: false,
      dialogTitle: '',
      info: {},
      form: {},
      updateForm: {},
      addForm: {},
      orderForm: {},
      operationTypeEnum: [{id: 1, name: "调拨"}, {id: 2, name: "采购"}],
      depositoryEnum: [],
      query: {},
      dugTypeTreeList: [],
      formRules: {
        operationType: [{ required: true, trigger: 'blur', validator: validateOperationType }],
        // type: [{ required: true, trigger: 'blur', validator: validateType }],
        // dept: [{ required: true, trigger: 'blur', validator: validateDept }],
      },
      orderFormRules: {
        auditPreset: [{ required: true, trigger: 'blur', validator: validateAuditPreset }],
        supplier: [{ required: true, trigger: 'blur', validator: validateSupplier }]
      },
      searchValue: '',
      isCommit: false,
      tableFilter: [],
      suppliers:[],
      auditPreset: [],
      isReUpdate: false,
    }
    
  },
  created() {
    this.fetchData()
  },
  methods: {
	components: { template },
    fetchData() {
      console.log("routers params",this.$route.params)
      this.orderForm = this.$route.params
      this.isCommit = this.orderForm.status === 1
      if(this.orderForm.id) {
        getPurchaseOrderInfo(this.orderForm.id).then(res=> {
          console.log("purchaseInfo", res.data)
          this.orderForm = res.data
          this.list = this.orderForm.purchaseOrderDrugList
          this.list[0].drugDepositoryVoList.forEach((item)=> {
            this.tableFilter.push({
              label: item.name
            })
          })
          this.depositoryEnum = this.list[0].drugDepositoryVoList
          if(res.data.auditFlowDetail.jobDutyList && res.data.auditFlowDetail.jobDutyList.length != 0) this.auditPreset = res.data.auditFlowDetail.jobDutyList
          this.listLoading = false
        })
      } else {
        allDrugDepositoryNum().then(res=> {
          console.log("res: ", res)
          this.orderForm = res.data
          this.list = this.orderForm.purchaseOrderDrugList
          this.list[0].drugDepositoryVoList.forEach((item)=> {
            this.tableFilter.push({
              label: item.name
            })
          })
          this.depositoryEnum = this.list[0].drugDepositoryVoList
          this.listLoading = false
        })
      }
      getSupplierList().then(supplierRes => {
        console.log(supplierRes)
        this.suppliers = supplierRes.data
      })
      getAuditInfo({businessCode: 'purchase_order'}).then(res=> {
        this.auditPreset = res.data
      })
    },
    cancel() {
      this.$router.push({ path: '/store/purchaseOrderAll' })
    },
    cancelOperation () {
      this.form.operationList = []
      this.formVisible = false
      this.updateForm.operationList = []
      this.updateFormVisible = false
      this.addForm.operationList = []
      this.addFormVisible = false
    },
    search() {
      this.listLoading = true
      this.currentPage = 1
      const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          depositoryIds: this.query.depositoryId
      }
      queryDepositoryNumList(reqBody).then(response=>{
        console.log(response)
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    confirm(type) {
      this.orderForm.status = type
      console.log(">>>", this.auditPreset)
      this.orderForm.auditUserIds = this.auditPreset.map(jobDutyVo => jobDutyVo.auditUser.id ? Number(jobDutyVo.auditUser.id) : Number(jobDutyVo.auditUser))
      console.log(this.orderForm)
      this.$refs.orderForm.validate(valid => {
        if (valid) {
          addorupdate(this.orderForm).then(res=> {
            console.log("addorupdate", res)
            this.orderForm.id = res.data.id
            if(type === 0) {
              this.$message.success("保存成功")
            } else {
              this.$message.success("提交成功")
              this.$router.push({ path: '/store/purchaseOrderAll' })
            }
          }).catch(err=>{
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          this.commitBtnLoading = false
          return false
        }
      })

      
    },
    operation(row, index) {
      this.reset()
      console.log("row:", row)
      this.dialogTitle = '采集/调拨'
      this.form = JSON.parse(JSON.stringify(row))
      this.form.index = index
      if(!this.form.operationList) this.$set(this.form, 'operationList', [])
      this.formVisible = true
    },
    updateOperation(row, index) {
      this.reset()
      console.log("row:", row)
      this.dialogTitle = '修改'
      this.updateForm = JSON.parse(JSON.stringify(row))
      this.updateForm.index = index
      if(!this.updateForm.operationList) this.$set(this.updateForm, 'operationList', [])
      this.searchValue = row.drugName + '/' + row.drugCommonName
      this.updateFormVisible = true
    },
    confirmOperation() {
      var drugDepositoryVoList = this.list[this.form.index].drugDepositoryVoList
      drugDepositoryVoList.forEach(item=> {
        item.doneInventory = item.inventory
        item.purchaseNum = 0
      })
      for (let index = 0; index < this.form.operationList.length; index++) {
        const operation = this.form.operationList[index];
        var sourceDepository = drugDepositoryVoList.filter(vo => vo.id === operation.sourceDepositoryId)[0] // 拿到了这个药品的来源库库
        var targetDepository = drugDepositoryVoList.filter(vo => vo.id === operation.targetDepositoryId)[0] // 拿到了这个药品的目标库
        if(operation.operationType === 1 && !operation.sourceDepositoryId) {
            this.$message.error('调拨时必须选择来源库')
            throw Error("调拨时必须选择来源库")
        }
        if(operation.sourceDepositoryId === operation.targetDepositoryId) {
            this.$message.error('来源库与目标库相同')
            throw Error("来源库与目标库相同")
        }
        if (operation.operationType === 1) {
          // 调拨
          if(sourceDepository.inventory < operation.num) {
            this.$message.error('库存不足,现有数量:' + sourceDepository.inventory)
            throw Error("库存不足")
          }
          // sourceDepository.operationList.add('调出至'+targetDepository.name + operation.num)
          sourceDepository.doneInventory = sourceDepository.inventory - operation.num
          targetDepository.doneInventory = Number(targetDepository.inventory) + Number(operation.num)
        } else {
          // 采购
          targetDepository.doneInventory = Number(targetDepository.doneInventory) + Number(operation.num)
          targetDepository.purchaseNum = Number(targetDepository.purchaseNum) + Number(operation.num)
        }
      }
      this.list[this.form.index].operationList = this.form.operationList
      this.formVisible = false
    },
    confirmUpdateOperation() {
      drugDepositoryNum({drugCode: this.updateForm.drugCode}).then(res=> {
        console.log("res", res)
        this.list.splice(this.updateForm.index, 1, res.data)
        var drugDepositoryVoList = this.list[this.updateForm.index].drugDepositoryVoList
        drugDepositoryVoList.forEach(item=> {
          item.doneInventory = item.inventory
          item.purchaseNum = 0
        })
        for (let index = 0; index < this.updateForm.operationList.length; index++) {
          const operation = this.updateForm.operationList[index];
          var sourceDepository = drugDepositoryVoList.filter(vo => vo.id === operation.sourceDepositoryId)[0] // 拿到了这个药品的来源库库
          var targetDepository = drugDepositoryVoList.filter(vo => vo.id === operation.targetDepositoryId)[0] // 拿到了这个药品的目标库
          if(operation.operationType === 1 && !operation.sourceDepositoryId) {
              this.$message.error('调拨时必须选择来源库')
              throw Error("调拨时必须选择来源库")
          }
          if(operation.sourceDepositoryId === operation.targetDepositoryId) {
              this.$message.error('来源库与目标库相同')
              throw Error("来源库与目标库相同")
          }
          if (operation.operationType === 1) {
            // 调拨
            if(sourceDepository.inventory < operation.num) {
              this.$message.error('库存不足,现有数量:' + sourceDepository.inventory)
              throw Error("库存不足")
            }
            // sourceDepository.operationList.add('调出至'+targetDepository.name + operation.num)
            sourceDepository.doneInventory = sourceDepository.inventory - operation.num
            targetDepository.doneInventory = Number(targetDepository.inventory) + Number(operation.num)
          } else {
            // 采购
            targetDepository.doneInventory = Number(targetDepository.doneInventory) + Number(operation.num)
            targetDepository.purchaseNum = Number(targetDepository.purchaseNum) + Number(operation.num)
          }
        }
        this.list[this.updateForm.index].operationList = this.updateForm.operationList
        this.isReUpdate = true
        this.updateFormVisible = false
      })
    },
    reset(){
      this.form = {}
      this.updateForm = {}
      this.addForm = {}
    },
    clickOperationType(operation) {
      this.$set(operation, "sourceDepositoryId", undefined)
      this.$set(operation, "num", undefined)
      this.$set(operation, "targetDepositoryId", undefined)
    },
    querySearch(queryString, cb) {
      getListByPinyinCode(queryString, this.query.depositoryId).then(drugListRes=>{
        // 调用 callback 返回建议列表的数据
        cb(drugListRes.data);
      })
    },
    handleSelect(item) {
      this.searchValue = item.name + '/' + item.commonName + ' ' + item.form + ' ' + item.specs + ' ' + item.factory
      console.log("searchValue", item)
      this.updateForm.drugCode = item.code
      this.updateForm.depositoryName = this.depositoryEnum[0].name
      this.updateForm.drugName = item.name
      this.updateForm.drugCommonName = item.commonName
      this.updateForm.drugSpecs = item.specs
      this.updateForm.form = item.form
      this.updateForm.inventory = 0
      this.updateForm.subInventory = 0
      this.updateForm.outerUnit = item.outerUnit
      this.updateForm.innerUnit = item.innerUnit
      this.updateForm.sellMethod = item.sellMethod
      this.updateForm.buyCycle = item.buyCycle
      this.updateForm.operationList = []
      
      this.addForm.drugCode = item.code
      this.addForm.depositoryName = this.depositoryEnum[0].name
      this.addForm.drugName = item.name
      this.addForm.drugCommonName = item.commonName
      this.addForm.drugSpecs = item.specs
      this.addForm.form = item.form
      this.addForm.inventory = 0
      this.addForm.subInventory = 0
      this.addForm.outerUnit = item.outerUnit
      this.addForm.innerUnit = item.innerUnit
      this.addForm.sellMethod = item.sellMethod
      this.addForm.buyCycle = item.buyCycle
      this.addForm.operationList = []
    },
    add() {
      this.reset()
      this.dialogTitle = '新增'
      this.$set(this.addForm, 'operationList', [])
      this.addFormVisible = true
    },
    confirmAddOperation() {
      drugDepositoryNum({drugCode: this.addForm.drugCode}).then(res=> {
        console.log("res", res)
        var drugDepositoryVoList = res.data.drugDepositoryVoList
        drugDepositoryVoList.forEach(item=> {
          item.doneInventory = item.inventory
          item.purchaseNum = 0
        })
        for (let index = 0; index < this.addForm.operationList.length; index++) {
          const operation = this.addForm.operationList[index];
          var sourceDepository = drugDepositoryVoList.filter(vo => vo.id === operation.sourceDepositoryId)[0] // 拿到了这个药品的来源库库
          var targetDepository = drugDepositoryVoList.filter(vo => vo.id === operation.targetDepositoryId)[0] // 拿到了这个药品的目标库
          if(operation.operationType === 1 && !operation.sourceDepositoryId) {
              this.$message.error('调拨时必须选择来源库')
              throw Error("调拨时必须选择来源库")
          }
          if(operation.sourceDepositoryId === operation.targetDepositoryId) {
              this.$message.error('来源库与目标库相同')
              throw Error("来源库与目标库相同")
          }
          if (operation.operationType === 1) {
            // 调拨
            if(sourceDepository.inventory < operation.num) {
              this.$message.error('库存不足,现有数量:' + sourceDepository.inventory)
              throw Error("库存不足")
            }
            // sourceDepository.operationList.add('调出至'+targetDepository.name + operation.num)
            sourceDepository.doneInventory = sourceDepository.inventory - operation.num
            targetDepository.doneInventory = Number(targetDepository.inventory) + Number(operation.num)
          } else {
            // 采购
            targetDepository.doneInventory = Number(targetDepository.doneInventory) + Number(operation.num)
            targetDepository.purchaseNum = Number(targetDepository.purchaseNum) + Number(operation.num)
          }
        }
        res.data.operationList = this.addForm.operationList
        this.list.push(res.data)
        this.isReUpdate = true
        this.addFormVisible = false
      })
      
    }
  }
}

</script>

<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .drug-input {
    width: 100%;
    display: inline-block;
    margin-right: 10px;
  }
  .drugs-item-title {
    line-height: 20px;
    text-align: center;
    background-color: #E4E7ED;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  .drugs-item {
    width: 140px;
    display: flex;
    flex-direction: column;
    margin-right: 20px;
  }
  .drug-name {
    width: 300px;
    word-wrap: break-word;
    margin-right: 20px;
    font-size: 15px;
    height: 58px;
    line-height: 58px;
  }

  .footer {
    display: flex;
    flex-direction: row;
    justify-content: center;
    margin: 50px;

  }
</style>@/api/checkRepository